<template>
  <view class="plan-page">
    <!-- 项目信息 -->
    <view class="project-info">
      <view class="info-header">
        <text class="project-name">{{ projectInfo.project_name }}</text>
        <text class="contract-number">{{ projectInfo.contract_number }}</text>
      </view>
      <view class="amount-info">
        <text class="amount-label">结算金额：</text>
        <text class="amount-value">¥{{ projectInfo.settlement_amount }}</text>
      </view>
    </view>

    <!-- 收款计划表单 -->
    <view class="form-card">
      <view class="form-header">
        <text class="form-title">收款计划设置</text>
      </view>
      
      <!-- 总期数 -->
      <view class="form-item">
        <text class="label">总收款期数</text>
        <input 
          v-model="planForm.total_periods" 
          class="input" 
          type="number"
          placeholder="请输入总期数"
        />
      </view>

      <!-- 收款节点列表 -->
      <view class="node-list">
        <view class="node-item" v-for="(node, index) in planForm.payment_nodes" :key="index">
          <view class="node-header">
            <text class="node-title">第{{ index + 1 }}期收款</text>
            <button class="delete-node-btn" @click="deletePaymentNode(index)" v-if="planForm.payment_nodes.length > 1">删除</button>
          </view>
          <view class="node-content">
            <view class="node-input-group">
              <view class="input-group">
                <text class="input-label">收款金额</text>
                <input 
                  v-model="node.amount" 
                  class="node-input" 
                  type="number"
                  placeholder="请输入金额"
                />
              </view>
              <view class="input-group">
                <text class="input-label">收款日期</text>
                <picker 
                  mode="date" 
                  :value="node.due_date" 
                  @change="(e) => onNodeDateChange(index, e)"
                >
                  <view class="node-picker">
                    <text>{{ node.due_date || '选择日期' }}</text>
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 添加节点按钮 -->
      <button class="add-node-btn" @click="addPaymentNode">+ 添加收款节点</button>

      <!-- 金额统计 -->
      <view class="amount-summary">
        <view class="summary-item">
          <text class="summary-label">计划总金额：</text>
          <text class="summary-value">¥{{ totalAmount }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">结算金额：</text>
          <text class="summary-value">¥{{ projectInfo.settlement_amount }}</text>
        </view>
        <view class="summary-item" :class="{ 'error': amountDiff !== 0 }">
          <text class="summary-label">差额：</text>
          <text class="summary-value">¥{{ amountDiff }}</text>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="savePlan" :disabled="!canSave">保存计划</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      projectId: null,
      projectInfo: {
        project_name: '华为总部建设项目',
        contract_number: 'HT2024001',
        settlement_amount: '480000'
      },
      planForm: {
        total_periods: 4,
        payment_nodes: [
          {
            amount: '120000',
            due_date: '2024-02-15'
          },
          {
            amount: '120000',
            due_date: '2024-03-15'
          },
          {
            amount: '120000',
            due_date: '2024-04-15'
          },
          {
            amount: '120000',
            due_date: '2024-05-15'
          }
        ]
      }
    }
  },
  computed: {
    totalAmount() {
      return this.planForm.payment_nodes.reduce((sum, node) => {
        return sum + (parseFloat(node.amount) || 0);
      }, 0);
    },
    amountDiff() {
      return this.totalAmount - parseFloat(this.projectInfo.settlement_amount);
    },
    canSave() {
      // 检查是否所有节点都有金额和日期
      return this.planForm.payment_nodes.every(node => 
        node.amount && node.due_date
      ) && this.amountDiff === 0;
    }
  },
  onLoad(options) {
    if (options.id) {
      this.projectId = options.id;
    }
    if (options.data) {
      try {
        const data = JSON.parse(decodeURIComponent(options.data));
        this.projectInfo = { ...this.projectInfo, ...data };
      } catch (error) {
        console.error('解析数据失败:', error);
      }
    }
    
    // 获取项目详情
    this.getProjectDetail();
  },
  methods: {
    async getProjectDetail() {
      try {
        // 这里调用获取项目详情的API
        console.log('获取项目详情:', this.projectId);
      } catch (error) {
        console.error('获取项目详情失败:', error);
      }
    },
    
    // 添加收款节点
    addPaymentNode() {
      this.planForm.payment_nodes.push({
        amount: '',
        due_date: ''
      });
      this.planForm.total_periods = this.planForm.payment_nodes.length;
    },
    
    // 删除收款节点
    deletePaymentNode(index) {
      this.planForm.payment_nodes.splice(index, 1);
      this.planForm.total_periods = this.planForm.payment_nodes.length;
    },
    
    // 节点日期变化
    onNodeDateChange(index, e) {
      this.planForm.payment_nodes[index].due_date = e.detail.value;
    },
    
    // 保存收款计划
    async savePlan() {
      // 表单验证
      if (this.planForm.payment_nodes.length === 0) {
        uni.showToast({ title: '请至少添加一个收款节点', icon: 'none' });
        return;
      }
      
      for (let i = 0; i < this.planForm.payment_nodes.length; i++) {
        const node = this.planForm.payment_nodes[i];
        if (!node.amount) {
          uni.showToast({ title: `请输入第${i + 1}期收款金额`, icon: 'none' });
          return;
        }
        if (!node.due_date) {
          uni.showToast({ title: `请选择第${i + 1}期收款日期`, icon: 'none' });
          return;
        }
      }
      
      if (this.amountDiff !== 0) {
        uni.showToast({ title: '计划总金额必须等于结算金额', icon: 'none' });
        return;
      }

      try {
        uni.showLoading({ title: '保存中...' });
        
        // 这里调用保存收款计划的API
        // const result = await savePaymentPlan({
        //   project_id: this.projectId,
        //   ...this.planForm
        // });
        
        // 模拟API调用
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({ title: '保存成功', icon: 'success' });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }, 2000);
        
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ title: '保存失败，请重试', icon: 'none' });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.plan-page {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 30rpx;
  box-sizing: border-box;
}

.project-info {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.info-header {
  margin-bottom: 20rpx;
}

.project-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.contract-number {
  font-size: 24rpx;
  color: #666;
}

.amount-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-label {
  font-size: 28rpx;
  color: #666;
}

.amount-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #409eff;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.form-header {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  display: block;
}

.input {
  width: 100%;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #fafafa;
  box-sizing: border-box;
  min-height: 80rpx;
}

.node-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.node-item {
  border: 1rpx solid #f0f0f0;
  border-radius: 12rpx;
  padding: 20rpx;
  background: #fafafa;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.node-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.delete-node-btn {
  background: #ff4d4f;
  color: #fff;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  border: none;
}

.node-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.node-input-group {
  display: flex;
  gap: 16rpx;
}

.input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.input-label {
  font-size: 24rpx;
  color: #666;
}

.node-input,
.node-picker {
  width: 100%;
  height: 60rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 26rpx;
  background: #fff;
  display: flex;
  align-items: center;
}

.node-picker text {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}

.add-node-btn {
  width: 100%;
  height: 80rpx;
  background: #f0f0f0;
  color: #666;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
  margin-bottom: 30rpx;
}

.amount-summary {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.summary-item:last-child {
  margin-bottom: 0;
  padding-top: 12rpx;
  border-top: 1rpx solid #e0e0e0;
}

.summary-label {
  font-size: 28rpx;
  color: #666;
}

.summary-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.summary-item.error .summary-value {
  color: #ff4d4f;
}

.submit-section {
  margin-top: 30rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: #409eff;
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  border: none;
}

.submit-btn:disabled {
  background: #ccc;
  color: #999;
}
</style> 